package com.meida.module.bus.provider.handler;

import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.interceptor.PageInterceptor;
import com.meida.common.mybatis.model.PageParams;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.module.bus.provider.service.BusDeptService;
import com.meida.module.bus.provider.service.BusProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import java.util.List;


/**
 * @Description 项目数据权限条件
 */
@Component("projectPageListHandler")
public class ProjectPageListHandler implements PageInterceptor {

    @Autowired
    private BusDeptService busDeptService;
    @Autowired
    BusProjectService busProjectService;


    @Override
    public void prepare(CriteriaQuery cq, PageParams pageParams, EntityMap params) {
        Long userId = OpenHelper.getUserId();
        boolean a = false;
        boolean b = false;
        List<String> userProjectIds = busProjectService.getUserProjectIds(userId);
        if (userProjectIds.size() > 0) {
            a = true;
            cq.in("project.projectId", userProjectIds);
        } else {
            List<String> userDeptList = busDeptService.getUserDepts(userId);
            if (userDeptList.size() > 0) {
                a = true;
                if (!userDeptList.contains("M00")) {
                    cq.apply("replace(project.deptProjectCode,',','|') regexp {0}", StringUtils.join(userDeptList, "|"));
                }
            }
        }
        EntityMap requestMap = cq.getRequestMap();
        if (a || b) {
            requestMap.put("isSet", true);
        } else {
            requestMap.put("isSet", false);
        }
        cq.setRequestMap(requestMap);
    }

    @Override
    public void complete(CriteriaQuery cq, List result, EntityMap extra) {
        EntityMap requestMap = cq.getRequestMap();
        Boolean isSet = requestMap.getBoolean("isSet");
        if (!isSet) {
            result.clear();
        }
    }

}
